package base.day25.ticket;

public class Ticket implements Runnable {
    private static int ticketCount = 100;
    //private static Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {
                //同步方法
                boolean result = synchronizedMehtod();
                if (result) {
                    break;
                }
            }
            //同步代码块
            if (("窗口二".equals(Thread.currentThread().getName()))) {
                synchronized (Ticket.class) {//多线程必须使用同一把锁
                    if (ticketCount == 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName() + "在买票，还剩下" + ticketCount + "张");
                    }
                }
            }

        }
    }

    private static synchronized boolean synchronizedMehtod() {
        if (ticketCount == 0) {
            return true;
        }
        else {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName() + "在买票，还剩下" + ticketCount + "张");
            return false;
        }

    }
}
